import { asyncRoutes, constantRoutes, convertTree, filterMenu } from '@/router'
import { fetchMenus } from '@/api/role'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
/* function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
} */

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  // console.log(filterMenu(roles))
  roles.forEach(route => {
    /*  if (route.component === 'Layout') {
      route.component = Layout
    } */
    // route.component = Layout
    res.push(route)
  })
  /*    routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      if (route.component === 'Layout') {
        route.component = Layout
      }
      res.push(tmp)
    }
  })  */
  // console.log(res)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterMenu(roles)
        //
        convertTree(accessedRoutes, roles)
        /*  accessedRoutes.forEach(r => {
          ShowObjProperty(r)
        }) */

        // console.log(rolemenus)
        // console.log(accessedRoutes)
        // const ms = convertTree(accessedRoutes, roles)
        // console.log(accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }
    })
  },
  getmenus(menus) {
    return new Promise(resolve => {
      const menulist = filterMenu(menus)
      convertTree(menulist, menus)
      resolve(menulist)
    })
  },
  fetchMenuslist({ commit }, query) {
    return new Promise((resolve, reject) => {
      fetchMenus(query).then(response => {
        const { data } = response
        const { menus } = data
        // console.log(menus)
        resolve(menus)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
